<!-- 单价维护 -->
<template>
  <div class="app-container">
    <div v-show="showTable">
      <div class="tabs">
        <px-radio-group v-model="activeName" class="tabSwitch" @change="tabSelectHandler">
          <!-- <px-radio-button v-has="`${item.permision}`" v-for="item in tabsOption" :key="item.name" :label="item.name">{{ item.label }}</px-radio-button> -->
          <px-radio-button v-has="'ALL_ENERGY_PRICE_CONFIG_ELECTRICITY'" label="Electricity">电</px-radio-button>
          <px-radio-button v-has="'ALL_ENERGY_PRICE_CONFIG_WATER'" label="Water">水</px-radio-button>
          <px-radio-button v-has="'ALL_ENERGY_PRICE_CONFIG_NG'" label="Ng">天然气</px-radio-button>
          <px-radio-button v-has="'ALL_ENERGY_PRICE_CONFIG_HOT_STEAM'" label="HotSteam">蒸汽/热水</px-radio-button>
          <px-radio-button v-has="'ALL_ENERGY_PRICE_CONFIG_GAS'" label="Gas">大宗气</px-radio-button>
          <!-- <px-radio-button v-has="'ALL_ENERGY_PRICE_CONFIG_DIESEL'" label="Diesel">柴油</px-radio-button> -->
        </px-radio-group>
        <px-form ref="queryRef" class="custom-form-ui-new" :model="queryParams" :inline="true" label-width="68px">
          <!-- <px-form-item label="生效时间" style="width: 460px">
            <px-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="defaultTime"
            />
          </px-form-item> -->
          <px-form-item label="生效开始时间" prop="effectiveStartTime" style="width: 300px">
            <px-date-picker
              v-model="queryParams.effectiveStartTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="开始时间"
              :default-time="defaultStartTime"
              @change="startTimeQuery"
            />
          </px-form-item>
          <px-form-item label="生效结束时间" prop="effectiveEndTime" style="width: 300px">
            <px-date-picker
              v-model="queryParams.effectiveEndTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="结束时间"
              :default-time="defaultEndTime"
              @change="endTimeQuery"
            />
          </px-form-item>
          <px-form-item>
            <px-button type="primary" @click="getList">查询</px-button>
            <px-button @click="resetQuery">重置</px-button>
          </px-form-item>
        </px-form>
      </div>
      <div class="mb-4">
        <px-button v-has="'ALL_ENERGY_PRICE_CONFIG_ADD'" type="primary" @click="handleFn(null, 'ADD')">新增</px-button>
      </div>
      <div v-loading="tableLoading" class="table-content">
        <px-table
          :data="tableData"
          border
          show-overflow-tooltip
          height="calc(100vh - 330px)"
          :header-cell-style="{ background: '#e7eefb', color: '#000' }"
        >
          <px-table-column type="index" label="序号" fixed width="55" align="center" />
          <px-table-column prop="version" label="单价生效时间" align="center" min-width="150">
            <template #default="scope">
              <div>{{ scope.row.effectiveStartTime }}-{{ scope.row.effectiveEndTime }}</div>
            </template>
          </px-table-column>
          <px-table-column prop="version" label="单价版本" align="center" />
          <px-table-column prop="updateByName" label="更新人" align="center" />
          <px-table-column prop="updateTime" label="更新时间" align="center" min-width="160" />
          <px-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="scope">
              <px-tooltip content="查看" placement="top">
                <px-button v-has="'ALL_ENERGY_PRICE_CONFIG_VIEW'" link icon="View" type="primary" @click="handleFn(scope.row, 'VIEW')" />
              </px-tooltip>
              <px-tooltip content="编辑" placement="top">
                <px-button v-has="'ALL_ENERGY_PRICE_CONFIG_EDIT'" link icon="EditPen" type="primary" @click="handleFn(scope.row, 'EDIT')" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button v-has="'ALL_ENERGY_PRICE_CONFIG_DELETE'" link icon="Delete" type="danger" @click="handleDelete(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
          <template #empty>
            <px-empty :image-size="150" />
          </template>
        </px-table>
        <!-- <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" /> -->
      </div>
    </div>
    <div v-show="!showTable">
      <div class="add-btn">
        <px-button type="primary" :icon="ArrowLeft" @click="cancelFn">返回</px-button>
      </div>
      <div class="add-content">
        <px-form ref="detailRef" :rules="rules" :model="detailParams" :inline="true" class="base-info-form" label-width="160px" label-position="top">
          <ReCollapse class="mb-4" title="版本信息">
            <div class="form-item-con">
              <px-row>
                <px-col :span="8">
                  <px-form-item label="版本" prop="version">
                    <px-input
                      v-model="detailParams.version"
                      :disabled="fromDisabled"
                      maxlength="20"
                      show-word-limit
                      placeholder="请输入版本"
                      clearable
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="生效开始时间" prop="effectiveStartTime">
                    <px-date-picker
                      v-model="detailParams.effectiveStartTime"
                      type="datetime"
                      :disabled="fromDisabled"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="开始时间"
                      :default-time="defaultStartTime"
                      @change="startTimeChange"
                    />
                  </px-form-item>
                </px-col>
                <px-col :span="8">
                  <px-form-item label="生效结束时间" prop="effectiveEndTime">
                    <px-date-picker
                      v-model="detailParams.effectiveEndTime"
                      type="datetime"
                      :disabled="isAnyEdit"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="结束时间"
                      :default-time="defaultEndTime"
                      @change="endTimeChange"
                    />
                  </px-form-item>
                </px-col>
              </px-row>
            </div>
          </ReCollapse>
          <ReCollapse v-if="activeName === 'Electricity'" class="mb-4" title="电">
            <div class="form-item-con">
              <px-row>
                <px-col :span="8">
                  <px-form-item label="峰电电价（元/千瓦时）" prop="peak">
                    <px-input-number
                      v-model="detailParams.peak"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="谷电电价（元/千瓦时）" prop="valley">
                    <px-input-number
                      v-model="detailParams.valley"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="平电电价（元/千瓦时）" prop="flat">
                    <px-input-number
                      v-model="detailParams.flat"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="输配电价（元/千瓦时）" prop="transmission">
                    <px-input-number
                      v-model="detailParams.transmission"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <!-- <px-col :span="8">
                  <px-form-item label="需量电价（元/千瓦时）" prop="demand">
                    <px-input-number
                      v-model="detailParams.demand"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col> -->
                <px-col :span="8">
                  <px-form-item label="容量电费（元/千伏安·月）" prop="capacity">
                    <px-input-number
                      v-model="detailParams.capacity"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
              </px-row>
              <barTitle title="功率因数调整电费表" />
              <div class="mb-4">
                <px-button v-if="handleType !== 'VIEW'" v-has="'ALL_ENERGY_PRICE_CONFIG_ADD'" type="primary" @click="handleAddFn">新增</px-button>
              </div>
              <px-table :data="powerData" border show-overflow-tooltip :header-cell-style="{ background: '#e7eefb', color: '#000' }">
                <px-table-column prop="powerFactor" label="实际功率因数" align="center">
                  <template #default="scope">
                    <px-input-number
                      v-if="state.tableRowEditIndex === scope.$index && state.tableColumnEditIndex == scope.column.id"
                      ref="tableRowInputRef1"
                      v-model="scope.row.powerFactor"
                      :controls="false"
                      :precision="6"
                      :value-on-clear="0"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                      @blur="onInputTableBlur1(scope, scope.row.powerFactor)"
                    />
                    <div v-else class="eidt-row-p" style="cursor: pointer" @click="dbClickCell1(scope)">
                      {{ scope.row.powerFactor }}
                    </div>
                  </template>
                </px-table-column>
                <px-table-column prop="ratio" label="电费增减比例(%)" align="center">
                  <template #default="scope">
                    <px-input-number
                      v-if="state.tableRowEditIndex === scope.$index && state.tableColumnEditIndex == scope.column.id"
                      ref="tableRowInputRef2"
                      v-model="scope.row.ratio"
                      :controls="false"
                      :precision="6"
                      :value-on-clear="0"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                      @blur="onInputTableBlur2(scope, scope.row.ratio)"
                    />
                    <div v-else class="eidt-row-p" style="cursor: pointer" @click="dbClickCell2(scope)">
                      {{ scope.row.ratio }}
                    </div>
                  </template>
                </px-table-column>
                <px-table-column v-if="handleType !== 'VIEW'" label="操作" width="150" fixed="right" align="center">
                  <template #default="scope">
                    <px-tooltip content="删除" placement="top">
                      <px-button
                        v-has="'ALL_ENERGY_PRICE_CONFIG_DELETE'"
                        link
                        icon="Delete"
                        type="danger"
                        @click="handleDeleteFn(scope.row, scope.$index)"
                      />
                    </px-tooltip>
                  </template>
                </px-table-column>
                <template #empty>
                  <px-empty :image-size="80" />
                </template>
              </px-table>
            </div>
          </ReCollapse>
          <ReCollapse v-if="activeName === 'Water'" class="mb-4" title="水">
            <div class="form-item-con">
              <px-row>
                <px-col :span="8">
                  <px-form-item label="自来水单价（元/m³）" prop="running">
                    <px-input-number
                      v-model="detailParams.running"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="再生水单价（元/m³）" prop="reclaim">
                    <px-input-number
                      v-model="detailParams.reclaim"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
              </px-row>
            </div>
          </ReCollapse>
          <ReCollapse v-if="activeName === 'Ng'" class="mb-4" title="天然气">
            <div class="form-item-con">
              <px-row>
                <px-col :span="8">
                  <px-form-item label="采暖季单价（元/m³）" prop="heat">
                    <px-input-number
                      v-model="detailParams.heat"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="12">
                  <!-- <px-form-item label="采暖季单价开始时间" prop="heatStartTime">
                    <px-date-picker
                      v-model="detailParams.heatStartTime"
                      type="datetime"
                      :disabled="fromDisabled"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="开始时间"
                      :default-time="defaultStartTime"
                    />
                  </px-form-item> -->
                  <px-form-item label="采暖季单价生效范围" style="width: 460px" prop="heatStartTime">
                    <px-date-picker
                      v-model="dateRangeHotStart"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetimerange"
                      range-separator="-"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      :default-time="defaultTime"
                      :disabled="fromDisabled"
                      @change="hanleTimeChange1"
                    />
                  </px-form-item>
                </px-col>
                <!-- <px-col :span="8">
                  <px-form-item label="采暖季单价时间" prop="heatEndTime">
                    <px-date-picker
                      v-model="detailParams.heatEndTime"
                      type="datetime"
                      :disabled="fromDisabled"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="结束时间"
                      :default-time="defaultEndTime"
                      @change="endTimeChange1"
                    />
                  </px-form-item>
                </px-col> -->
                <px-col :span="8">
                  <px-form-item label="非采暖季单价（元/m³）" prop="nonHeat">
                    <px-input-number
                      v-model="detailParams.nonHeat"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <!-- <px-form-item label="非采暖季单价开始时间" prop="nonHeatStartTime">
                    <px-date-picker
                      v-model="detailParams.nonHeatStartTime"
                      type="datetime"
                      :disabled="fromDisabled"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="开始时间"
                      :default-time="defaultStartTime"
                    />
                  </px-form-item> -->
                  <px-form-item label="非采暖季单价生效范围" style="width: 460px" prop="nonHeatStartTime">
                    <px-date-picker
                      v-model="dateRangeHotEnd"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetimerange"
                      range-separator="-"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      :default-time="defaultTime"
                      :disabled="fromDisabled"
                      @change="hanleTimeChange2"
                    />
                  </px-form-item>
                </px-col>
                <!-- <px-col :span="8">
                  <px-form-item label="非采暖季单价时间" prop="nonHeatEndTime">
                    <px-date-picker
                      v-model="detailParams.nonHeatEndTime"
                      type="datetime"
                      :disabled="fromDisabled"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="结束时间"
                      :default-time="defaultEndTime"
                      @change="endTimeChange2"
                    />
                  </px-form-item>
                </px-col> -->
              </px-row>
            </div>
          </ReCollapse>
          <ReCollapse v-if="activeName === 'HotSteam'" class="mb-4" title="蒸汽/热水">
            <div class="form-item-con">
              <px-row>
                <px-col :span="8">
                  <px-form-item label="蒸汽单价（元/t）" prop="steam">
                    <px-input-number
                      v-model="detailParams.steam"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="蒸汽最低用量（元/h）" prop="steamMin">
                    <!-- <px-input
                      v-model="detailParams.steamMin"
                      :disabled="fromDisabled"
                      oninput="value=value.replace(/[^0-9.]/g, '')"
                      placeholder="请输入最低用量"
                      clearable
                    />  -->
                    <px-input-number
                      v-model="detailParams.steamMin"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入最低用量"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="热水单价（元/GJ）" prop="hotWater">
                    <px-input-number
                      v-model="detailParams.hotWater"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="热水最低用量（元/h）" prop="hotWaterMin">
                    <!-- <px-input
                      v-model="detailParams.hotWaterMin"
                      :disabled="fromDisabled"
                      oninput="value=value.replace(/[^0-9.]/g, '')"
                      placeholder="请输入最低用量"
                      clearable
                    />  -->
                    <px-input-number
                      v-model="detailParams.hotWaterMin"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入最低用量"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
              </px-row>
            </div>
          </ReCollapse>
          <ReCollapse v-if="activeName === 'Gas'" class="mb-4" title="大宗气">
            <div class="form-item-con">
              <px-row>
                <px-col :span="8">
                  <px-form-item label="N₂单价（元/Nm³）" prop="n2">
                    <px-input-number
                      v-model="detailParams.n2"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="H₂单价（元/Nm³）" prop="h2">
                    <px-input-number
                      v-model="detailParams.h2"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="O₂单价（元/Nm³）" prop="o2">
                    <px-input-number
                      v-model="detailParams.o2"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="Ar单价（元/Nm³）" prop="ar">
                    <px-input-number
                      v-model="detailParams.ar"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="He单价（元/Nm³）" prop="he">
                    <px-input-number
                      v-model="detailParams.he"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="CO₂单价（元/Nm³）" prop="co2">
                    <px-input-number
                      v-model="detailParams.co2"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="CDA单价（元/Nm³）" prop="cda">
                    <px-input-number
                      v-model="detailParams.cda"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
              </px-row>
              <barTitle title="设备租赁费" />
              <div class="mb-4">
                <!-- <px-button v-if="handleType !== 'VIEW'" v-has="'ALL_ENERGY_PRICE_CONFIG_ADD'" type="primary" @click="handleAddFn1">新增</px-button> -->
              </div>
              <px-table :data="eqpCostData" border show-overflow-tooltip :header-cell-style="{ background: '#e7eefb', color: '#000' }">
                <px-table-column prop="date" label="时间" align="center" />
                <px-table-column prop="deviceFee" label="设备租赁费(元)" align="center">
                  <template #default="scope">
                    <px-input-number
                      v-if="state.tableRowEditIndex === scope.$index && state.tableColumnEditIndex == scope.column.id"
                      ref="tableRowInputRef3"
                      v-model="scope.row.deviceFee"
                      :controls="false"
                      :precision="6"
                      :value-on-clear="0"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                      @blur="onInputTableBlur3(scope, scope.row.deviceFee)"
                    />
                    <div v-else class="eidt-row-p" style="cursor: pointer" @click="dbClickCell3(scope)">
                      {{ scope.row.deviceFee }}
                    </div>
                  </template>
                </px-table-column>
                <!-- <px-table-column v-if="handleType !== 'VIEW'" label="操作" width="150" fixed="right" align="center">
                  <template #default="scope">
                    <px-tooltip content="删除" placement="top">
                      <px-button
                        v-has="'ALL_ENERGY_PRICE_CONFIG_DELETE'"
                        link
                        icon="Delete"
                        type="danger"
                        @click="handleDeleteFn1(scope.row, scope.$index)"
                      />
                    </px-tooltip>
                  </template>
                </px-table-column> -->
                <template #empty>
                  <px-empty :image-size="80" />
                </template>
              </px-table>
            </div>
          </ReCollapse>
          <ReCollapse v-if="activeName === 'Diesel'" class="mb-4" title="柴油">
            <div class="form-item-con">
              <px-row>
                <px-col :span="8">
                  <px-form-item label="柴油单价（元/t）" prop="diesel">
                    <px-input-number
                      v-model="detailParams.diesel"
                      :disabled="fromDisabled"
                      :controls="false"
                      :min="0"
                      :precision="6"
                      :value-on-clear="0"
                      placeholder="请输入价格"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                    /> </px-form-item
                ></px-col>
              </px-row>
            </div>
          </ReCollapse>
        </px-form>
      </div>
      <div v-if="isShowReTeleport">
        <ReTeleport>
          <div class="replace-bottle-add-teleport-btns">
            <px-button @click="cancelFn">取消</px-button>
            <px-button v-if="handleType !== 'VIEW'" type="primary" @click="confirmFn">保存</px-button>
          </div>
        </ReTeleport>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_ENERGY_COST_PRICE_CONFIG"
});
import { PxMessage, PxMessageBox } from "px-ui";
import { ref, reactive, computed, toRefs, onMounted, nextTick, getCurrentInstance } from "vue";
import { type OptionsType } from "@/components/ReSegmented";
import { getPriceList, updatePrice, viewPrice, delPrice } from "@/api/energy/priceConfig";
import barTitle from "@/views/machine/components/barTitle/index.vue";
import ReTeleport from "@/components/ReTeleport";
import ReCollapse from "@/components/ReCollapse";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRouterStoreHook } from "@/store/modules/router";

const { proxy }: any = getCurrentInstance();

const showTable = ref(true);
const tableLoading = ref(false);
const fromDisabled = ref(false);
const isShowReTeleport = ref(false);
const detailParams = ref<any>({});

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];

const defaultStartTime: Date = new Date(2000, 1, 1, 0, 0, 0);
const defaultEndTime: Date = new Date(2000, 1, 1, 23, 59, 59);

const tabsOption = ref<Array<any>>([
  {
    name: "Electricity",
    label: "电",
    permision: "ALL_ENERGY_PRICE_CONFIG_ELECTRICITY"
  },
  {
    name: "Water",
    label: "水",
    permision: "ALL_ENERGY_PRICE_CONFIG_WATER"
  },
  {
    name: "Ng",
    label: "天然气",
    permision: "ALL_ENERGY_PRICE_CONFIG_NG"
  },
  {
    name: "HotSteam",
    label: "蒸汽/热水",
    permision: "ALL_ENERGY_PRICE_CONFIG_HOT_STEAM"
  },
  {
    name: "Gas",
    label: "大宗气",
    permision: "ALL_ENERGY_PRICE_CONFIG_GAS"
  },
  {
    name: "Diesel",
    label: "柴油",
    permision: "ALL_ENERGY_PRICE_CONFIG_DIESEL"
  }
]);

const activeName = ref("Electricity");

const paramsActiveName = computed(() => {
  if (activeName.value === "HotSteam") return "hotSteam";
  return activeName.value.toLowerCase();
});

const handleType = ref("ADD");
const dateRange = ref([]);
const dateRangeHotStart = ref([]);
const dateRangeHotEnd = ref([]);
const tableRowInputRef1: any = ref(null);
const tableRowInputRef2: any = ref(null);
const tableRowInputRef3: any = ref(null);

const state = reactive({
  queryParams: {
    // pageNum: 1,
    // pageSize: 10,
    effectiveStartTime: "",
    effectiveEndTime: "",
    type: paramsActiveName
  },
  tableRowEditIndex: undefined,
  tableColumnEditIndex: undefined,
  tableData: [],
  rules: {
    version: [{ required: true, message: "请输入版本", trigger: "blur" }],
    effectiveStartTime: [{ required: true, message: "请选择时间", trigger: "blur" }],
    effectiveEndTime: [{ required: true, message: "请选择时间", trigger: "blur" }],
    peak: [{ required: true, message: "请输入价格", trigger: "blur" }],
    valley: [{ required: true, message: "请输入价格", trigger: "blur" }],
    flat: [{ required: true, message: "请输入价格", trigger: "blur" }],
    transmission: [{ required: true, message: "请输入价格", trigger: "blur" }],
    demand: [{ required: true, message: "请输入价格", trigger: "blur" }],
    capacity: [{ required: true, message: "请输入价格", trigger: "blur" }],
    running: [{ required: true, message: "请输入价格", trigger: "blur" }],
    reclaim: [{ required: true, message: "请输入价格", trigger: "blur" }],
    heat: [{ required: true, message: "请输入价格", trigger: "blur" }],
    heatStartTime: [{ required: true, message: "请选择时间", trigger: "blur" }],
    // heatEndTime: [{ required: true, message: "请选择时间", trigger: "blur" }],
    nonHeat: [{ required: true, message: "请输入价格", trigger: "blur" }],
    nonHeatStartTime: [{ required: true, message: "请选择时间", trigger: "blur" }],
    // nonHeatEndTime: [{ required: true, message: "请选择时间", trigger: "blur" }],
    steam: [{ required: true, message: "请输入价格", trigger: "blur" }],
    steamMin: [{ required: true, message: "请输入用量", trigger: "blur" }],
    hotWater: [{ required: true, message: "请输入价格", trigger: "blur" }],
    hotWaterMin: [{ required: true, message: "请输入用量", trigger: "blur" }],
    n2: [{ required: true, message: "请输入价格", trigger: "blur" }],
    h2: [{ required: true, message: "请输入价格", trigger: "blur" }],
    o2: [{ required: true, message: "请输入价格", trigger: "blur" }],
    ar: [{ required: true, message: "请输入价格", trigger: "blur" }],
    he: [{ required: true, message: "请输入价格", trigger: "blur" }],
    co2: [{ required: true, message: "请输入价格", trigger: "blur" }],
    cda: [{ required: true, message: "请输入价格", trigger: "blur" }],
    diesel: [{ required: false, message: "请输入价格", trigger: "blur" }]
  },
  total: 0,
  powerData: [],
  eqpCostData: []
});
const { queryParams, tableData, rules, total, powerData, eqpCostData } = toRefs(state);

const isAnyEdit = ref(false);

const tabSelectHandler = (selectName: string) => {
  activeName.value = selectName;
  getList();
};

const hanleTimeChange1 = val => {
  detailParams.value.heatStartTime = val ? val[0] : "";
  detailParams.value.heatEndTime = val ? val[1] : "";
};
const hanleTimeChange2 = val => {
  detailParams.value.nonHeatStartTime = val ? val[0] : "";
  detailParams.value.nonHeatEndTime = val ? val[1] : "";
};

// 双击可编辑的单元格
const dbClickCell1 = (scope: any) => {
  // 找到单个格子独有的属性 - 这里是用所在行跟列id区别显示
  state.tableRowEditIndex = scope.$index;
  state.tableColumnEditIndex = scope.column.id;
  nextTick(() => {
    // 获取焦点
    tableRowInputRef1.value.focus();
  });
};
// 双击可编辑的单元格
const dbClickCell2 = (scope: any) => {
  // 找到单个格子独有的属性 - 这里是用所在行跟列id区别显示
  state.tableRowEditIndex = scope.$index;
  state.tableColumnEditIndex = scope.column.id;
  nextTick(() => {
    // 获取焦点
    tableRowInputRef2.value.focus();
  });
};
// 双击可编辑的单元格
const dbClickCell3 = (scope: any) => {
  console.log(scope);
  console.log(activeName.value, fromDisabled.value);
  if (activeName.value === "Gas" && fromDisabled.value) {
    return;
  }
  // 找到单个格子独有的属性 - 这里是用所在行跟列id区别显示
  state.tableRowEditIndex = scope.$index;
  state.tableColumnEditIndex = scope.column.id;
  nextTick(() => {
    // 获取焦点
    tableRowInputRef3.value.focus();
  });
};

// 表格中input取消焦点,select变化
const onInputTableBlur1 = (scope: any, val: string | number) => {
  console.log("取消焦点", scope);
  state.tableRowEditIndex = undefined;
  state.tableColumnEditIndex = undefined;
  val = val ? val : 0;
  const id = scope.row.id;
  const key = scope.column.property;
  const value = scope.row[key];
  // 更新给后端的数据接口
  // 提交数据........
};
// 表格中input取消焦点,select变化
const onInputTableBlur2 = (scope: any, val: string | number) => {
  console.log("取消焦点", scope);
  state.tableRowEditIndex = undefined;
  state.tableColumnEditIndex = undefined;
  val = val ? val : 0;
  const id = scope.row.id;
  const key = scope.column.property;
  const value = scope.row[key];
  // 更新给后端的数据接口
  // 提交数据........
};
// 表格中input取消焦点,select变化
const onInputTableBlur3 = (scope: any, val: string | number) => {
  console.log("取消焦点", scope);
  state.tableRowEditIndex = undefined;
  state.tableColumnEditIndex = undefined;
  val = val ? val : 0;
  scope.row.deviceFee = scope.row.deviceFee ? scope.row.deviceFee : "-";
  const id = scope.row.id;
  const key = scope.column.property;
  const value = scope.row[key];
  // 更新给后端的数据接口
  // 提交数据........
};

// 功率因数新增
const handleAddFn = () => {
  powerData.value.push({
    powerFactor: 0,
    ratio: 0
  });
};
// 功率因数删除
const handleDeleteFn = (row, index) => {
  if (powerData.value && powerData.value.length) {
    powerData.value.splice(index, 1);
  }
};

// 设备租赁费新增
const handleAddFn1 = () => {
  eqpCostData.value.push({
    date: "",
    deviceFee: 0
  });
};
// 设备租赁费删除
const handleDeleteFn1 = (row, index) => {
  if (eqpCostData.value && eqpCostData.value.length) {
    eqpCostData.value.splice(index, 1);
  }
};

/** 列表 */
const getList = async () => {
  // if (!queryParams.value.effectiveStartTime && !queryParams.value.effectiveEndTime) {
  //   PxMessage.warning("请选择开始时间");
  //   return;
  // }
  tableLoading.value = true;
  // const res: any = await getPriceList(proxy.addDateRange(queryParams.value, dateRange.value, "effectiveStartTime", "effectiveEndTime"));
  const res: any = await getPriceList(queryParams.value);
  res?.forEach(i => {
    i.effectiveEndTime = i.effectiveEndTime.split(" ")[0];
    i.effectiveStartTime = i.effectiveStartTime.split(" ")[0];
  });
  tableData.value = res || [];
  // total.value = res?.total;
  tableLoading.value = false;
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [];
  proxy.$refs["queryRef"].resetFields();
  getList();
};

const startTimeQuery = (val: any) => {
  if (queryParams.value.effectiveEndTime && new Date(val) > new Date(queryParams.value.effectiveEndTime)) {
    PxMessage.warning("开始时间不能大于结束时间");
    queryParams.value.effectiveStartTime = null;
    return;
  }
};
const endTimeQuery = (val: any) => {
  if (!queryParams.value.effectiveStartTime) {
    PxMessage.warning("请选择开始时间");
    queryParams.value.effectiveEndTime = null;
    return;
  }
  if (new Date(queryParams.value.effectiveStartTime) > new Date(val)) {
    PxMessage.warning("开始时间不能大于结束时间");
    queryParams.value.effectiveEndTime = null;
    return;
  }
};

const getMonthsRange = (start, end) => {
  const months = [];
  const currentDate = new Date(start);
  const endDate = new Date(end);
  while (currentDate <= endDate) {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1;
    months.push(`${year}-${month.toString().padStart(2, "0")}`);
    currentDate.setMonth(currentDate.getMonth() + 1);
  }
  return months;
};

const startTimeChange = (val: any) => {
  if (detailParams.value.effectiveEndTime && new Date(val) > new Date(detailParams.value.effectiveEndTime)) {
    PxMessage.warning("开始时间不能大于结束时间");
    detailParams.value.effectiveStartTime = null;
    return;
  }
  if (detailParams.value.effectiveEndTime) {
    // 计算时间段内的月份list
    const monthList = getMonthsRange(detailParams.value.effectiveStartTime, detailParams.value.effectiveEndTime);
    const monthArr = monthList.map(item => {
      return {
        date: item,
        deviceFee: "-"
      };
    });
    if (eqpCostData.value.length) {
      eqpCostData.value = mergeArray(monthArr, eqpCostData.value);
    } else {
      eqpCostData.value = monthArr;
    }
  }
};

const endTimeChange = (val: any) => {
  if (!detailParams.value.effectiveStartTime) {
    PxMessage.warning("请选择开始时间");
    detailParams.value.effectiveEndTime = null;
    return;
  }
  if (new Date(detailParams.value.effectiveStartTime) > new Date(val)) {
    PxMessage.warning("开始时间不能大于结束时间");
    detailParams.value.effectiveEndTime = null;
    return;
  }

  // 计算时间段内的月份list
  const monthList = getMonthsRange(detailParams.value.effectiveStartTime, detailParams.value.effectiveEndTime);
  const monthArr = monthList.map(item => {
    return {
      date: item,
      deviceFee: "-"
    };
  });
  if (eqpCostData.value.length) {
    eqpCostData.value = mergeArray(monthArr, eqpCostData.value);
  } else {
    eqpCostData.value = monthArr;
  }
};

const mergeArray = (arr1, arr2) => {
  const itemMap = new Map(arr2.map(item => [item.date, item]));
  return arr1.map(item1 => {
    if (itemMap.has(item1.date)) {
      return itemMap.get(item1.date);
    }
    return item1;
  });
};

const endTimeChange1 = (val: any) => {
  if (!detailParams.value.heatStartTime) {
    PxMessage.warning("请选择开始时间");
    detailParams.value.heatEndTime = null;
    return;
  }
  if (new Date(detailParams.value.heatStartTime) > new Date(val)) {
    PxMessage.warning("开始时间不能大于结束时间");
    detailParams.value.heatEndTime = null;
    return;
  }
};

const endTimeChange2 = (val: any) => {
  if (!detailParams.value.nonHeatStartTime) {
    PxMessage.warning("请选择开始时间");
    detailParams.value.nonHeatEndTime = null;
    return;
  }
  if (new Date(detailParams.value.nonHeatStartTime) > new Date(val)) {
    PxMessage.warning("开始时间不能大于结束时间");
    detailParams.value.nonHeatEndTime = null;
    return;
  }
};

// 新增/编辑
const handleFn = async (row: any, type: string) => {
  handleType.value = type;
  powerData.value = [];
  eqpCostData.value = [];
  isShowReTeleport.value = true;
  nextTick(() => {
    proxy.$refs["detailRef"].clearValidate();
  });
  detailParams.value = {};
  dateRangeHotStart.value = [];
  dateRangeHotEnd.value = [];
  if (type !== "ADD") {
    const res: any = await viewPrice({ id: row.id }, activeName.value);
    powerData.value = res.power && res.power.length ? res.power : [];
    eqpCostData.value =
      res.deviceFee && res.deviceFee.length
        ? res.deviceFee.map(e => {
            return {
              date: e.date.substring(0, 7),
              deviceFee: e.deviceFee ? e.deviceFee : "-"
            };
          })
        : [];
    detailParams.value = JSON.parse(JSON.stringify(res));
    dateRangeHotStart.value = [detailParams.value.heatStartTime || "", detailParams.value.heatEndTime || ""];
    dateRangeHotEnd.value = [detailParams.value.nonHeatStartTime || "", detailParams.value.nonHeatEndTime || ""];
    if (type === "VIEW") {
      fromDisabled.value = true;
      isAnyEdit.value = true;
      showTable.value = false;
    } else {
      if (detailParams.value.effectiveEndTime) {
        const validateT1 = new Date().getTime() > new Date(detailParams.value.effectiveEndTime).getTime();
        const validateT2 =
          new Date(detailParams.value.effectiveStartTime).getTime() <= new Date().getTime() &&
          new Date().getTime() <= new Date(detailParams.value.effectiveEndTime).getTime(); // 生效中 可编辑生效结束时间 和 月租费
        console.log(
          new Date(detailParams.value.effectiveStartTime).getTime(),
          new Date(detailParams.value.effectiveEndTime).getTime(),
          new Date().getTime(),
          validateT1,
          validateT2
        );
        if (validateT1) {
          fromDisabled.value = true;
          isAnyEdit.value = true;
          showTable.value = false;
          return;
        }
        if (validateT2) {
          fromDisabled.value = true;
          isAnyEdit.value = false;
          showTable.value = false;
          return;
        }
        fromDisabled.value = false;
        isAnyEdit.value = false;
        showTable.value = false;
      } else {
        const validateT2 = new Date(detailParams.value.effectiveStartTime).getTime() <= new Date().getTime(); // 结束时间为空默认无限大
        if (validateT2) {
          fromDisabled.value = true;
          isAnyEdit.value = false;
          showTable.value = false;
          return;
        }
        fromDisabled.value = false;
        isAnyEdit.value = false;
        showTable.value = false;
      }
    }
  } else {
    fromDisabled.value = false;
    isAnyEdit.value = false;
    showTable.value = false;
  }
};

/** 删除按钮操作 */
const handleDelete = (row: any) => {
  const validateT1 = new Date().getTime() >= new Date(row.effectiveStartTime).getTime() || !row.effectiveStartTime;
  if (validateT1) {
    PxMessage.warning("已生效或生效中不可删除！");
    return;
  }
  PxMessageBox.confirm(`是否确认删除版本为${row.version}的数据项？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "px-button--danger",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delPrice({ id: row.id }, activeName.value);
      PxMessage.success("删除成功");
      getList();
    })
    .catch(() => {});
};

/** 保存按钮操作 */
const confirmFn = () => {
  const params = Object.assign({}, detailParams.value);
  if (powerData.value && powerData.value.length) {
    params.power = powerData.value;
  }
  if (eqpCostData.value && eqpCostData.value.length) {
    params.deviceFee = eqpCostData.value.map(item => {
      return {
        date: item.date + "-01 00:00:00",
        deviceFee: item.deviceFee === "-" ? null : item.deviceFee
      };
    });
  }
  proxy.$refs["detailRef"].validate(valid => {
    if (!valid) return;
    PxMessageBox.confirm(`请一定保证单价数据的准确性，保存后相关计算数据生成无法修正，继续保存吗？`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(async () => {
        await updatePrice(params, activeName.value);
        PxMessage.success("保存成功");
        const routeStore = useRouterStoreHook();
        routeStore.SET_BOTTOM_FOOTER_HEIGHT(0);
        isShowReTeleport.value = false;
        showTable.value = true;
        getList();
      })
      .catch(() => {});
  });
};

// 返回/取消
const cancelFn = () => {
  if (handleType.value === "VIEW") {
    isShowReTeleport.value = false;
    const routeStore = useRouterStoreHook();
    routeStore.SET_BOTTOM_FOOTER_HEIGHT(0);
    showTable.value = true;
  } else {
    PxMessageBox.confirm(`数据未保存，是否退出？`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(() => {
        isShowReTeleport.value = false;
        const routeStore = useRouterStoreHook();
        routeStore.SET_BOTTOM_FOOTER_HEIGHT(0);
        showTable.value = true;
      })
      .catch(() => {});
  }
};

onMounted(async () => {
  await getList();
});
</script>

<style lang="scss" scoped>
.hidden {
  display: none;
}

.tabs {
  /*
    * tab样式
    */
  .tabSwitch {
    padding: 4px;
    margin-bottom: 16px;
    background-color: #f4f4f4;
    border-radius: 4px;

    :deep(.px-radio-button__inner) {
      background-color: #f4f4f4;
      border: none;
    }

    :deep(.is-active) {
      border: none;

      .px-radio-button__inner {
        background-color: var(--px-color-primary);
        border-radius: 4px;
      }
    }
  }
}

.replace-bottle-add-teleport-btns {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 100%;
  padding: 16px;
}

.add-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 16px;

  .base-info-form {
    box-sizing: border-box;

    .form-item-con {
      padding: 16px;

      .year-month {
        display: flex;
        height: 72px;

        :deep(.px-input) {
          display: flex !important;
          flex-flow: column nowrap !important;
          height: 36px !important;
        }

        :deep(.px-input-group__prepend) {
          border-right: 1px !important;
          border-radius: 4px !important;
        }

        :deep(.px-form-item) {
          margin: 0;
        }

        :deep(.px-form-item__error) {
          position: absolute;
          top: 100%;
          left: 0;
          padding-top: 2px;
          font-size: 12px;
          line-height: 1;
          color: var(--px-color-danger);
        }
      }
    }

    .px-form-item {
      .px-select {
        width: 100%;
      }

      .px-input {
        width: 100%;
      }

      :deep(.px-date-editor) {
        width: 100%;
      }
    }
  }
}

:deep(.px-input-number) {
  width: 100%;
}

:deep(.px-input__inner) {
  text-align: left;
}

.month-text {
  width: 100%;
  text-align: center;
  border: 1px solid #ccc;
  border-bottom: none;
  border-radius: 4px;
}
</style>
